package com.slipper.system.codeless.controller;

import com.slipper.core.gson.GsonUtil;
import com.slipper.system.affix.service.AffixItemService;
import com.slipper.system.codeless.bo.TemplateBO;
import com.slipper.system.codeless.bo.TemplateFolderBO;
import com.slipper.system.codeless.service.TemplateFolderService;
import com.slipper.system.codeless.vo.TemplateVO;
import com.slipper.core.tree.Node;
import com.slipper.core.tree.Tree;
import com.slipper.core.tree.TreeInfo;
import com.slipper.core.tree.TreeUtil;
import com.slipper.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.slipper.system.codeless.service.TemplateService;
import com.slipper.constants.Constants;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * 模板信息表
 */
@RestController
@RequestMapping("/system/template")
public class TemplateController {
    private static final Logger logger = LoggerFactory.getLogger(TemplateController.class);

    @Resource
    private TemplateService templateService;
    @Resource
    private TemplateFolderService templateFolderService;
    @Resource
    private AffixItemService affixItemService;

    @PostMapping(value = "/queryBy")
    public String queryBy(@RequestBody TemplateBO bo) {
        if(Tool.isBlank(bo.getId())) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(templateService.queryBy(bo.getId()));
    }

    @PostMapping(value = "/queryList")
    public String queryList(@RequestBody TemplateBO bo) {
        return ResultUtil.successResult(templateService.queryList(bo));
    }

    @PostMapping(value = "/queryPage")
    public String queryPage(@RequestBody TemplateBO bo) {
        return ResultUtil.successResult(templateService.queryPage(bo));
    }

    @PostMapping("/queryTree")
    public String queryTree() {
        List<TemplateFolderBO> folderList = templateFolderService.queryList(new TemplateFolderBO());
        TreeInfo folderTreeInfo = new TreeInfo("模板");
        folderTreeInfo.setRootId(Constants.ROOT_ID);
        folderTreeInfo.setIdField("id");
        folderTreeInfo.setPidField("parentId");
        folderTreeInfo.setTextField("name");
        folderTreeInfo.setNodeType("folder");
        folderTreeInfo.setSortField("ordinal");

        List<TemplateBO> templateList = templateService.queryList(new TemplateBO());
        TreeInfo templateTreeInfo = new TreeInfo("");
        templateTreeInfo.setIdField("id");
        templateTreeInfo.setPidField("folderId");
        templateTreeInfo.setTextField("name");
        templateTreeInfo.setNodeType("template");
        templateTreeInfo.setSortField("ordinal");

        Node rootNode = TreeUtil.buildTree(
                "asc",
                new Tree(folderTreeInfo, BeanUtil.setOrdinal(folderList)),
                new Tree(templateTreeInfo, BeanUtil.setOrdinal(templateList, folderList.size())));
        return ResultUtil.successResult(rootNode);
    }

    @PostMapping(value = "/save")
    public String save(@RequestBody TemplateBO bo) {
        if (Tool.isBlank(bo.getName())) {
            return ResultUtil.failureResult("变量名不能为空！");
        }

        bo.setOperateId(Constants.getCurrentUser().getEmployeeId());
        return ResultUtil.saveResult(templateService.save(bo), bo);
    }

    @PostMapping(value = "/delete")
    public String delete(@RequestBody TemplateBO bo) {
        return ResultUtil.successResult(templateService.delete(bo));
    }

    @PostMapping(value = "/exportData")
    public void exportData(HttpServletResponse response, @RequestBody TemplateBO bo) {
        TemplateVO template = new TemplateVO();
        if (bo.getIds() != null && bo.getIds().length > 0) {
            TemplateFolderBO folderQO = new TemplateFolderBO();
            folderQO.setIds(bo.getIds());
            template.setFolderList(templateFolderService.queryList(folderQO));

            TemplateBO templateQO = new TemplateBO();
            templateQO.setFolderIds(bo.getIds());
            template.setTemplateList(templateService.queryList(templateQO));
            String[] ids = template.getTemplateList()
                    .stream()
                    .map(TemplateBO::getFileId)
                    .toList()
                    .toArray(new String[0]);
            template.getFileList().addAll(affixItemService.queryWithFile(ids));
        }

        String fileName = "template-" + DateUtil.format(new Date(), "dd-HH-mm-ss") + ".dat";
        FileUtil.downloadContent(response, fileName, AESUtil.encrypt(GsonUtil.toJson(template)));
    }

    @PostMapping(value = "/importData")
    public String importData(TemplateBO bo) {
        if (bo.getFile() == null) {
            return ResultUtil.failureResult("请选择上传文件！");
        }

        try {
            String content = new String(bo.getFile().getBytes(), StandardCharsets.UTF_8);
            TemplateVO vo = GsonUtil.fromJson(AESUtil.decrypt(content), TemplateVO.class);
            templateFolderService.saveList(vo.getFolderList());
            templateService.saveList(vo.getTemplateList());
            affixItemService.saveList(vo.getFileList());
            return ResultUtil.successResult("导入模板成功。");
        } catch (Exception e) {
            logger.error("文件保存出错！", e);
            return ResultUtil.failureResult("文件保存出错！");
        }
    }
}
